/*
 * Gedigarr - Falling block game.
 * Copyright (C) 2010  BoredCorp
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
package putil;

/**
 *
 * @author JC
 */
public class Putil {

  /**
   * Used to wrap array indexes. uBound is the upper boundary of the array, 
   * target is the potential new array index. If the index is %gt uBound then the
   * index is wrapped to 0+remainder. if it is %lt 0 it is wrapped to 
   * uBound-remainder
   * @param indexes The upper of array elements
   * @param target The new potential array index.
   * @return A normalised array index guaranteed not to be out of bounds
   */
  public static int wrapIndex( int indexes, int target ) {
    int index = target;
    if ( target >= indexes ) {
      index = indexes % target;// % uBound;
    } else if ( target < 0 ) {
      index = indexes - 1;
    }
    return index;
  }

  public static int bindIndex( int indexes, int target ) {
    indexes--;
    if ( target > indexes ) {
      return indexes;
    } else if ( target < 0 ) {
      return 0;
    }
    return target;
  }

  /**
   * Modifies the bitMask supplied by changing the value of bit.<br>
   * If true, then the specified bit will be 1, it will be 0 if false.
   *
   * @param bitMask The bitmask to modify
   * @param bit The bit to modify (0 = least significant)
   * @param b Set the bit: true = 1, false = 0.
   */
  public static int setBitState( int bitMask, int bit, boolean b ) {
    if ( b ) {
      //turn on bit
      bitMask = bitMask | bit;
    } else {
      //turn off bit
      bitMask = bitMask & ~bit;
    }
    return bitMask;
  }

  public static boolean isBitSet( int bitMask, int bit ) {
    return ( bit & bitMask ) == bit;
  }

  public static void main( String[] args ) {
    for ( int i = 0; i < 5; i++ ) {
      System.out.println( bindIndex( 5, i ));
    }
  }
}
